/*
 * #%L
 * java model
 * %%
 * Copyright (C) 2009 - 2011 Stefan Isele
 * %%
 * All Rights Reserved.
 * This program is dual-licensed under the GNU General Public license
 * or a commercial license.
 * You may select to use one or the other of these licenses.
 * To obtain a commercial license please contact Stefan Isele at www.stefan-isele.de
 * Any modifications to this file must keep this entire header intact.
 * Redistribution, except as permitted by the selected license, is prohibited.
 * #L%
 */
package com.prefabware.jmodel.code;

import com.prefabware.commons.QualifiedName;

public class CodeBuffer {
	private StringBuffer buffer;
	private JCodeOptions options;
	private boolean insertLeadingSpace;

	public void setInsertLeadingSpace(boolean insertLeadingSpace) {
		this.insertLeadingSpace = insertLeadingSpace;
	}

	public CodeBuffer(JCodeOptions options) {
		super();
		this.options = options;
		this.buffer = new StringBuffer();
		this.insertLeadingSpace=true;
	}

	public CodeBuffer append(JCodable fragment) {
		this.append(fragment.asCode(options));
		return this;
	}
	public CodeBuffer append(QualifiedName fragment) {
		this.append(options.asCode(fragment));
		return this;
	}

	/**
	 * appends the fragment to this CodeBuffer.
	 * Trims all leading and trailing whitespaces.
	 * if {@link #insertLeadingSpace}==true, inserts a single whitespace before each fragment, except the first one.
	 * if the fragment==null nothing will be appended
	 * if the fragment is empty or contains only whitespace, nothing will be appended
	 * 
	 * @param fragment
	 * @return
	 */
	public CodeBuffer append(String fragment) {
		if (isNotNullOrEmpty(fragment)) {
			if (buffer.length() > 0) {
				if (insertLeadingSpace) {
					
				//insert a white space before each fragment
				//excpet the first one
				buffer.append(" ");
				}
			}
			buffer.append(fragment.trim());
		}
		return this;
	}

	protected boolean isNotNullOrEmpty(String fragment) {
		return fragment != null && !fragment.trim().isEmpty();
	}

	/**
	 * @param condition the element that must not be null or empty
	 * @param fragments the fragments to append if the condition is not null or empty
	 * @return
	 */
	public CodeBuffer appendIfNotNullOrEmpty(String condition,
			String... fragments) {
		if (isNotNullOrEmpty(condition)) {
			for (String fragment : fragments) {
				append(fragment);
			}
		}
		return this;
	}

	@Override
	public String toString() {
		return buffer.toString().trim();
	}

}
